# -*- coding: utf-8 -*-

import simplejson
from decimal import Decimal

class PyProtocol(object):
    @staticmethod
    def serialize(data):
        return simplejson.dumps(data,cls=PyProtocolSerializeableEncoder)
    
    @staticmethod
    def deserialize(sdata):
        return simplejson.loads(sdata, object_hook=decodePyProtocolSerializeable)

class PyProtocolSerializeable(object):
    def serializeToDict(self):
        d = {'_PyProtocolSerializeable': True}
        if hasattr(self,'_serializeable'):
            for n in self._serializeable:
                d[n] = getattr(self,n)
        return d

    def deserializeFromDict(self,d):
        for n,v in d.items():
            setattr(self,n,v)

class PyProtocolSerializeableEncoder(simplejson.JSONEncoder):
    def encode(self,obj):
        if isinstance(obj,PyProtocolSerializeable):
            return obj.serializeToDict()
        if isinstance(obj, Decimal):
            return float(obj)
        if isinstance(obj, str) or isinstance(obj, unicode):
            return "'%s'"%obj
        return simplejson.JSONEncoder.encode(self,obj)

def decodePyProtocolSerializeable(dct):
    if '_PyProtocolSerializeable' in dct:
        return PyProtocolSerializeable().deserializeFromDict(dct)
    return dct
